package com.aaa.os.consumer;

import com.aaa.common.entity.ProductOrder;
import com.aaa.common.vo.ProductOrderVO;
import com.aaa.os.config.RabbitMQConfig;
import com.aaa.os.service.ProductOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.io.IOException;

/**
 * @FileName: OrderTimeoutConsumer
 * @Description: 订单超时处理
 * @Author: CH
 * @CreateTime: 2025/10/17 15:10
 * @Version: 1.0.0
 */
@Component
@Log4j2
public class OrderTimeoutConsumer {
    @Resource
    private ProductOrderService productOrderService;

    // 监听死信队列，处理未支付的订单
    //在配置文件中配置了手动确认模式，所以这里需要手动确认消息
    @RabbitListener(queues = RabbitMQConfig.DEAD_LETTER_QUEUE)
    public void handleOrderTimeout(String orderId, Channel channel, Message message) throws IOException {
        log.info("订单超时处理开始，订单ID：{}", orderId);
        try {
            // 1. 查询订单
            ProductOrderVO productOrderVO = productOrderService.queryById(Integer.parseInt(orderId));
            if (productOrderVO == null) {
                log.warn("订单不存在，订单ID：{}", orderId);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); // 确认消息
                return;
            }
            // 2. 订单状态为【待支付】时，处理订单超时
            if (productOrderVO.getStatusCode() == 11) {
                log.info("订单超时处理开始，订单ID：{}", orderId);
                ProductOrder updateOrder = new ProductOrder();
                updateOrder.setId(productOrderVO.getId());
                updateOrder.setStatusCode(30);  //订单超时取消
                productOrderService.update(updateOrder);
                log.info("订单超时处理结束，订单ID：{}", orderId);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,false);
            log.error("处理超时订单失败", e);
            e.printStackTrace();
        }
    }
}
